package com.pbe;


import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * Created by lenovo on 2016/1/7.
 */
public class ImoocPBE {
    private static String src = "imooc security pbe";

    public static void main(String[] args){

        jdkPBE();
    }

    public static void jdkPBE(){

        try {
            //初始化
            SecureRandom random = new SecureRandom();
            byte[] bytes = random.generateSeed(8);

            //口令与密钥
            String password = "imooc";
            PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray());
            SecretKeyFactory factory = SecretKeyFactory.getInstance("PBEWITHMD5andDES");
            Key key = factory.generateSecret(pbeKeySpec);

            //加密
            PBEParameterSpec pbeParameterSpec = new PBEParameterSpec(bytes,100);
            Cipher cipher = Cipher.getInstance("PBEWITHMD5andDES");
            cipher.init(Cipher.ENCRYPT_MODE,key,pbeParameterSpec);
            byte[] bytes1 = cipher.doFinal(src.getBytes());
            System.out.println("jdk pbe encrypt : "+ Base64.encodeBase64String(bytes1));

            //解密
            cipher.init(Cipher.DECRYPT_MODE,key,pbeParameterSpec);
            bytes1 = cipher.doFinal(bytes1);
            System.out.println("jdk pbe decrypt : "+ new String(bytes1));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
